﻿using log4net.Core;
using Org.BouncyCastle.Tls.Crypto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.UnifyResult.Exceptions
{
    public class BusinessException : Exception
    {
        /// <summary>
        /// 错误代码
        /// </summary>
        public string ErrorCode { get; set; }
        
        /// <summary>
        /// 基础构造函数
        /// </summary>
        /// <param name="message"></param>
        public BusinessException(string message) : base(message)
        {
        }

        /// <summary>
        /// 带有错误代码的构造函数
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        public BusinessException(string errorCode, string message):base(message) { 
            ErrorCode = errorCode;        
        }

        // 带内部异常的构造函数
        public BusinessException(string message, Exception innerException) : base(message, innerException)
        {
        }

        // 序列化时保存自定义字段
        public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue(nameof(ErrorCode), ErrorCode);
        }
    }

    /// <summary>
    /// 业务异常抛出静态类
    /// </summary>
    public static class BusinessThrow
    {
        /// <summary>
        /// 基础异常抛出
        /// </summary>
        /// <param name="message"></param>
        /// <exception cref="BusinessException"></exception>
        public static void Throw( string message) {
            throw new BusinessException(message);
        }

        /// <summary>
        /// 错误代码抛出
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <exception cref="BusinessException"></exception>
        public static void Throw(string errorCode, string message)
        { 
            throw new BusinessException(errorCode, message);
        }
    }



    public static class BusinessExceptionExtensions
    {
        /// <summary>
        /// 抛出业务异常
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static BusinessException OBException(this string message) { 
        return new BusinessException(message);        
        }
    
    }
}
